package rt.crashmere.gateway.filters;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.jetbrains.annotations.NotNull;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import rt.crashmere.rpc.provider.InterfaceInfoProvider;
import rt.crashmere.rpc.provider.UserInterfaceInfoProvider;
import rt.crashmere.rpc.provider.UserProvider;
import rt.crashmere.sdk.utils.SignUtils;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 全局过滤
 *
 * @author Lwh
 */
@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    //    IP白名单
    public static final List<String> IP_WHITE_LIST = Collections.singletonList("127.0.0.1");

    @DubboReference
    private UserProvider userProvider;

    @DubboReference
    private InterfaceInfoProvider interfaceInfoProvider;

    @DubboReference
    private UserInterfaceInfoProvider userInterfaceInfoProvider;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = request.getHeaders();
        RequestPath path = request.getPath();
//        1. 统一请求日志
        log.info("请求id：" + request.getId());
        log.info("请求头：" + headers);
        log.info("请求Cookies：" + request.getCookies());
        log.info("请求类型：" + request.getMethodValue());
        log.info("请求参数：" + request.getQueryParams());
        log.info("请求源地址：" + request.getRemoteAddress());
        log.info("请求路径：" + path);
        log.info("请求URI：" + request.getURI());
//        2. 白名单
        String hostName = Objects.requireNonNull(request.getRemoteAddress()).getHostString();
        if (!IP_WHITE_LIST.contains(hostName)) {
            log.info("forbidden for: 该IP不在白名单中");
            return forbidden(response);
        }
//        3. ak,sk 鉴权
        String accessKey = headers.getFirst("accessKey");
        String sign = headers.getFirst("sign");
        String nonce = headers.getFirst("nonce");
        String timestamp = headers.getFirst("timestamp");
        if (StringUtils.isAnyBlank(accessKey, sign, nonce, timestamp)) {
            log.info("forbidden for: API签名参数含空");
            return forbidden(response);
        }
//        五分钟之前的请求
        long currentTime = System.currentTimeMillis() / 1000;
        long FIVE_MINUTE = 60 * 5L;
        if ((currentTime - Long.parseLong(Objects.requireNonNull(timestamp))) >= FIVE_MINUTE) {
            log.info("forbidden for: 请求发出时间间隔过久");
            return forbidden(response);
        }
//        TODO 验证随机数是否重复
        if (StringUtils.isBlank(nonce)) {
            log.info("forbidden for: 随机数已存在");
            return forbidden(response);
        }
//        从库中查询sk
        String secretKey = userProvider.getSecretKey(accessKey);
        if (StringUtils.isBlank(secretKey) || !SignUtils.genSign(secretKey, accessKey).equals(sign)) {
            log.info("forbidden for: API签名非法");
            return forbidden(response);
        }
//        4. 判断请求的接口是否存在
        int interfaceId = interfaceInfoProvider.getInterfaceIdByPath(path.toString());
        if (interfaceId == 0) {
            log.info("forbidden for: 请求接口不存在");
            return forbidden(response);
        }
        int userId = userProvider.getUserIdByAccessKey(accessKey);

//        5. 请求转发，调用模拟接口 + 响应日志
        return handleResponse(exchange, chain, userId, interfaceId);
    }

    /**
     * 处理响应
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain,
                                     int userId, int interfaceId) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 缓存数据的工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 拿到响应码
            HttpStatus statusCode = originalResponse.getStatusCode();
            if (statusCode == HttpStatus.OK) {
                // 装饰，增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                    // 等调用完转发的接口后才会执行
                    @NotNull
                    @Override
                    public Mono<Void> writeWith(@NotNull Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        // 往返回值里写数据
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            return super.writeWith(
                                    fluxBody.map(dataBuffer -> {
                                        byte[] content = new byte[dataBuffer.readableByteCount()];
                                        dataBuffer.read(content);
                                        DataBufferUtils.release(dataBuffer);//释放内存
                                        // 6. 调用成功，接口调用次数 + 1 invokeCount
                                        try {
                                            userInterfaceInfoProvider.invokeCount(interfaceId, userId);
                                        } catch (Exception e) {
                                            log.info("更新调用次数失败");
                                            throw new RuntimeException("更新调用次数失败");
                                        }
                                        // 7. 打印日志
                                        String data = new String(content, StandardCharsets.UTF_8);
                                        log.info("响应结果：" + data);
                                        return bufferFactory.wrap(content);
                                    })
                            );
                        } else {
                            // 8. 调用失败，返回一个规范的错误码
                            log.error("<--- {} 响应code异常", getStatusCode());
                            return super.writeWith(body);
                        }
                    }
                };
                // 设置 response 对象为装饰过的
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange); // 降级处理返回数据
        } catch (Exception e) {
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }

    private static Mono<Void> forbidden(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return -1;
    }
}

